﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TomNet.Core.Options;
using TomNet.Exceptions;
using TomNet.Extensions;
using TomNet.Caching;

namespace TomNet.Redis
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddRedis(this IServiceCollection services)
        {
            IConfiguration configuration = services.GetConfiguration();
            var _IotOptions = configuration.GetTomNetOptions();


            if (_IotOptions?.Redis?.Enabled != true)
            {
                return services;
            }

            string config = _IotOptions.Redis.Configuration;
            if (config.IsNullOrEmpty())
            {
                throw new TomNetException("配置文件中Redis节点的Configuration不能为空");
            }
            string name = _IotOptions.Redis.InstanceName;


            //services.RemoveAll(typeof(IDistributedCache));
            //var csredis = new CSRedis.CSRedisClient(config + ",prefix=" + name);
            //RedisHelper.Initialization(csredis);
            //services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));


            var csredis = new CSRedis.CSRedisClient(config + ",prefix=" + name);
            RedisHelper.Initialization(csredis);
            services.AddSingleton<ICache, RedisCache>();

            return services;
        }
    }
}
